package com.hzf.wxplatform.admin.runnable;

import com.hzf.common.util.HttpUtil;
import com.hzf.common.util.PropertiesFileUtil;
import com.hzf.common.util.RedisUtil;
import net.sf.json.JSONObject;

/**
 * 扫描微信token的线程
 * 启动时候获取token,然后每隔45分钟刷新一次token
 * @author xdx
 *
 */
public class TokenScan {
    public static void main(String[] args) {
                Runner1 runner1 = new Runner1();
                Thread thread2 = new Thread(runner1);
                thread2.start();
            }


}

class Runner1 implements Runnable {

    public boolean run = true;// 线程开关
    private static final int cycle = 45;//刷新周期，45min刷新一次


    @Override
    public void run() {
        String appid = "wx7146b48eb53f7a2f";
        String appsecret = "de131f8fbd30a5bde239fa843f0c1552";

        while (run) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
            String tokenStr = HttpUtil.getTokenByUrl(url);
            System.out.println("获取到了:"+tokenStr);
            JSONObject tokeJson = JSONObject.fromObject(tokenStr);
            if (tokeJson.containsKey("access_token")) {
                String access_token = tokeJson.getString("access_token");
                RedisUtil.del_add("access_token", access_token);
                String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
                        + access_token + "&type=jsapi";
                String ticketStr = HttpUtil.getTokenByUrl(ticketUrl);
                JSONObject ticketJson = JSONObject.fromObject(ticketStr);
                if (ticketJson.containsKey("ticket")) {
                    String jsapi_ticket = ticketJson.getString("ticket");
                    RedisUtil.del_add("jsapi_ticket", jsapi_ticket);
                }
                //api_ticket
                String apiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=wx_card";
                String apiTickerStr = HttpUtil.getTokenByUrl(apiTicketUrl);
                JSONObject apiTicketJson = JSONObject.fromObject(apiTickerStr);
                if (apiTicketJson.containsKey("ticket")) {
                    String api_ticket = apiTicketJson.getString("ticket");
                    RedisUtil.del_add("api_ticket", api_ticket);
                }
            }
            try {
                Thread.sleep(cycle * 60 * 1000);//3600000
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}




